﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using log4net;

namespace AirlineServer
{
    public class FlightsServer
    {
        private readonly ILog log = LogManager.GetLogger(typeof(FlightsDatabase));

        private readonly List<Flight> flights;

        public FlightsServer(string name, IEnumerable<Flight> flights)
        {
            Name = name;

            this.flights = new List<Flight>(flights);

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Loaded {0} flights from collection", this.flights.Count);
            }
        }

        public FlightsServer(string name, Stream s)
        {
            Name = name;

            flights = new List<Flight>();

            using (var reader = new StreamReader(s))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    var items = line.Split(' ');

                    flights.Add(new Flight
                    {
                        Airline = name,
                        FlightId = items[0],
                        From = items[1],
                        To = items[2],
                        Date = DateTime.ParseExact(items[3], "dd/MM/yyyy", CultureInfo.CurrentCulture),
                        Price = int.Parse(items[4]),
                    });
                }
            }

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Loaded {0} flights from stream", flights.Count);
            }
        }

        public string Name { get; set; }

        public IEnumerable<Flight> Flights
        {
            get { return flights; }
        }
    }
}
